package org.subatu.orm.service.base;


import org.subatu.orm.query.base.OrderEnum;
import org.subatu.orm.query.function.FunctionToQueryColumnUtil;
import org.subatu.orm.query.function.SFunction;
import org.subatu.orm.query.table.QueryColumn;

/**
 * 查询
 */
public interface OrderBy extends BaseQuery {

    // orderBy 部分的sql
    // StringBuilder orderBySql = new StringBuilder();

    default <E> BaseQuery orderBy(SFunction<E>... columns) {
        try {
            System.err.println(this.sqlData().fromTable);
            System.err.println(this.sqlData().selectList);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return this.orderByDesc(columns);
    }

    default <E> BaseQuery orderByDesc(SFunction<E>... columns) {
        return this.orderBy(OrderEnum.DESC, columns);
    }

    default <E> BaseQuery orderByAsc(SFunction<E>... columns) {
        return this.orderBy(OrderEnum.ASC, columns);
    }

    default <E> BaseQuery orderBy(OrderEnum orderEnum, SFunction<E>... columns) {
        for (SFunction<E> column : columns) {
            this.orderBy(column, orderEnum);
        }
        return (BaseQuery) this;
    }

    default <E> BaseQuery orderBy(SFunction<E> function, OrderEnum orderEnum) {
        QueryColumn column = FunctionToQueryColumnUtil.getQueryColumn(function);
        sqlData().orderByList.put(column, orderEnum);
        return (BaseQuery) this;
    }

    default BaseQuery orderBy(String sql) {
        // 加入到查询队列
        sqlData().orderBySql.setLength(0);
        sqlData().orderBySql.append(" order by ");
        sqlData().orderBySql.append(sql);
        sqlData().orderBySql.append(' ');
        return (BaseQuery) this;
    }

    default String buildOrderBySql() {
        if (sqlData().orderBySql.length() > 0 || sqlData().orderByList.size() == 0) {
            // 如果手工设置了 sql, 直接返回
            return sqlData().orderBySql.toString();
        }

        // 组装 sql
        sqlData().orderBySql.setLength(0);
        sqlData().orderBySql.append(" order by ");

        // 组装所有 列
        sqlData().orderByList.forEach((queryColumn, orderEnum) -> {
            String tableAlias = this.sqlData().tableAliasMap.get(queryColumn.getTable().getTableName());
            String columnSql = queryColumn.buildOrderBySql(tableAlias, orderEnum);
            sqlData().orderBySql.append(columnSql);
        });

        // 去掉 列 最后的逗号
        sqlData().orderBySql.deleteCharAt(sqlData().orderBySql.length() - 1);
        sqlData().orderBySql.append(' ');

        return sqlData().orderBySql.toString();
    }
}
